/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-02-26 15:19:36
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-15 11:45:13
 */

class JvMap {
  constructor() {
    this.length = 0
    this.first_key=''
    this.data = {}
  }
  [Symbol.iterator](){
    return this.data
  }
  set(key,val){
    if(!this.length) this.first_key = key
    if(!this.data[key]){
      this.data[key] = val
      this.length++
    } 
  }
  get(key){
    return this.data[key]
  }
  remove(key){
    delete this.data[key]
    this.length--
  }
  size(){
    return this.length
  }
  getFirst(){
    return this.get(this.first_key)
  }
  
}
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const returnStatus = res => {
  return new Promise((resolve, reject) => {
    if (res.code === 200) {
      // 成功
      resolve(res.data?res.data:res.data===null?res.message:true)
    } else {
      reject(res)
    }
  })
}
const returnStatusToast = (res, cbk, err) => {
  if (res.code === 200) {
    wx.showToast({
      title: res.title||res.message||'操作成功',
      icon: 'none',
      duration: 500,
      mask: false,
      success: (result) => {
        setTimeout(() => {
          typeof cbk === 'function' && cbk()
        }, 500);
      },
      fail: () => {},
      complete: () => {}
    });
  } else {
    wx.showToast({
      title:res.message,
      icon:'none'
    })
    typeof err === "function" && err(res.message)
  }
}

import { goodsAPI, orderAPI } from '../api/index'
const handleCollect  = function(productId,collect,target){
  const type = collect ? "NO" : "YES"
  goodsAPI.handleCollect({
    productId,
    type
  }).then(async _ => {
    await returnStatus(_)
    const isCollect = type !== "NO"
    wx.showToast({
      title: `${isCollect?'收藏':'取消收藏'}成功`,
      icon:'none',
      duration: 800,
    });
    this.setData({
      [target]: isCollect
    })
  })
}
const getSkuInfo = function(productId,goodsInfo){
  goodsAPI.queryGoodsSaleInfo({
    productId
  }).then(async res=>{
    const saleInfo = await returnStatus(res)
    
    let sizeData = new JvMap()
    let colorData = new JvMap()
    let saleSKU = new JvMap()
    let total_stock=0
    saleInfo.forEach(item=>{
      saleSKU.set(`${item.productColor}_${item.productSize}`,item)
      sizeData.set(item.productSize, item.productSize)
      colorData.set(item.productColor, item.productColor)
      total_stock+=item.storageQuantity
    })
    this.setData({
      saleInfo:{
        sizeData:sizeData.data,
        colorData:colorData.data,
        saleSKU:saleSKU.data,
        colorAlias:goodsInfo.colorAlias,
        sizeAlias:goodsInfo.sizeAlias,
        price: goodsInfo.priceDuration,
        sizeVal: sizeData.size()===1?sizeData.getFirst():'',
        colorVal: colorData.size()===1?sizeData.getFirst():'',
        total_stock
      }
    })
    this.setSku()
  })
}

const getPromise = function(info,info_key,config){
  const params = config.params
  // {
  //   productId:this.data.productId
  // }
  let promise =[]
  info.forEach(item=>{
    promise.push(
      new Promise((resolve, reject) => {
       config.API[item](params).then(async res=>{
        const _ = await returnStatus(res)
        _?resolve(_):reject(false)
      })
    }))
  })
  return Promise.all(promise).then(res=>{
    res.forEach((item,index)=>{
      const key = info_key[index]
      this.setData({
        [key]:item
      })
    })
  })
}
const afterNav = function(info,status){
  // 售后
  var afterStatus = {
    "null": "申请售后",
    "1": "等待审核",
    "2": "填写单号",
    "3": "等待收货",
    "4": "等待退款",
    "5": "申请失败",
    "6": "申请失败",
    "7": "退款成功"
  }
  const msgMap = {
    0: `申请已经提交，正在等待${status===4?'财务':'客服'}审核请耐心等待…`,
    1: `售后编号：6849354898，您申请的售后已被拒绝，原因为：无具体原由`,
    2: `退货运单号已经提交，正在等待仓库收货，验收无误后财务将原路退回售后金额，请耐心等待…`
  }
  const api = {
    '1': `?status=1&message=${msgMap[0]}`,
    '2': `?status=1&message=${msgMap[0]}`,
    '3': `?status=1&message=${msgMap[2]}`,
    '4': `?status=1&message=${msgMap[0]}`,
    '5': `?status=1&message=${msgMap[1]}`,
    '6': `?status=1&message=${msgMap[1]}`,
    null: ''
  }
  const param = (api[status]&&api[status]+`&title=${afterStatus[status]}`)||''
  wx.navigateTo({
    url: `/pages/mine/order/afterOrder/${status==null?'type':status===7?'action':'status'}/index${param}`,
    success: (res) => {
      res.eventChannel.emit('params', {
        info,
        read: status === 7
      })
    },
  })
  return false
}

/*函数节流*/
function throttle(fn, interval) {
  var enterTime = 0;//触发的时间
  var gapTime = interval || 300 ;//间隔时间，如果interval不传，则默认300ms
  return function() {
    var context = this;
    var backTime = new Date();//第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context,arguments);
      enterTime = backTime;//赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  };
}

/*函数防抖*/
var timer;
function debounce(fn, interval) {
  var gapTime = interval || 1000;//间隔时间，如果interval不传，则默认1000ms
  return function() {
    clearTimeout(timer);
    var context = this;
    var args = arguments;//保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function() {
      fn.call(context,args);
    }, gapTime);
  };
}

// 客户登录
function login(){
  wx.login({
    complete: ({code}) => {
      wx.getUserInfo({
        complete: ({userInfo}) => {
          userAPI.login({code,...userInfo}).then(({code,data})=>{
            if(code===200){
              wx.setStorage({
                data: data.token,
                key: 'token',
              })
              wx.setStorage({
                data: data&&data.userInfo,
                key: 'userInfo',
              })
            }
          })
        },
      })
    },
  })
}
async function payOrder(orderId,orderCode){
  let {data:{payInfo}} = await orderAPI.createOrderPay({
    orderId,
    payBy: 1,
    tradeType: 'JSAPI_MINI'
  })
  try {
    payInfo = JSON.parse(payInfo)
  } catch (error) {
    console.error('payInfo', '解析支付单出错')
  }
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      timeStamp: payInfo.timestamp,
      nonceStr: payInfo.nonce_str,
      package: `prepay_id=${payInfo.prepay_id}`,
      signType: 'MD5',
      paySign: payInfo.sign,
      success (res) { 
        wx.redirectTo({
          url: '/pages/payStatus/index?orderId='+orderId+'orderCode='+orderCode,
        })
        resolve(res)
      },
      fail (res) { 
        console.log('fail', res)
        reject(res)
      }
    })
  })
}
module.exports = {
  formatTime: formatTime,
  returnStatus,
  returnStatusToast,
  handleCollect,
  JvMap,
  getSkuInfo,
  getPromise,
  afterNav,
  throttle,
  debounce,
  login,
  payOrder
}